
package com.example.springbootlearn.config;

import com.example.springbootlearn.entity.MyselfMapper;
import com.example.springbootlearn.entity.MyselfMapper;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;

// 生成sql实现增删改查
public class ORMSession {
    private Connection connection;
    public ORMSession(Connection connection){
        this.connection = connection;
    }

    public void save(Object entity) throws SQLException, IllegalAccessException {
        String insertSQL = "";
        // 从ORMConfig中获得保存有映射信息的集合
        List<MyselfMapper> mapperList = ORMConfig.mapperList;
        //遍历集合，从集合中找到和entity参数相对应的mapper对象
        for (MyselfMapper mapper: mapperList) {
            if (mapper.getClassName().equals(entity.getClass().getName())) {
                String tableName = mapper.getTableName();
                String insertSql1 = "insert into " + tableName + "(";
                String insertSql2 = ") values (";
                //得到当前对象所属类中的所有属性
                Field[] fields = entity.getClass().getDeclaredFields();
                for (Field field: fields) {
                    field.setAccessible(true);
                    //遍历过程中根据属性得到字段名
                    String columnName = mapper.getPropMapper().get(field.getName());
                    //遍历过程中根据属性得到它的值
                    String columnValue = field.get(entity).toString();
                    //拼接sql语句
                    insertSql1 += columnName + ",";
                    insertSql2 += "'" + columnValue + "',";
                }
                insertSQL = insertSql1.substring(0,insertSQL.length() -1) + insertSql2.substring(0, insertSql2.length() -1) + ")";
                break;
            }
        }
        //把sql语句输出到控制台
        System.out.println("Mini-save" + insertSQL);
        // 通过jdbc执行sql语句
        PreparedStatement statement = connection.prepareStatement(insertSQL);
        statement.executeUpdate();
        statement.close();
    }
    // 删除操作
    public void delete(Object entity) throws NoSuchFieldException, SQLException, IllegalAccessException {
        String deleteSql = "delete from ";
//        获取映射信息集合
        List<MyselfMapper> mapperList = ORMConfig.mapperList;
        for (MyselfMapper mapper: mapperList) {
            if (mapper.getClassName().equals(entity.getClass().getName())) {
                // 获取表名
                String tableName = mapper.getTableName();
                deleteSql += tableName + "where";
                // 得到主键的字段名和属性名
                Object[] idprops = mapper.getIdMapper().keySet().toArray();
                Object[] idColumns = mapper.getIdMapper().values().toArray();

                // 得到主键的值
                Field field = entity.getClass().getDeclaredField(idprops[0].toString());
                field.setAccessible(true);
                String idvalue = field.get(entity).toString();

                deleteSql += idColumns[0] + " = " + idvalue;
                System.out.println("Mini-ORm delete:" + deleteSql);
                break;
            }
        }
        // 通过jdbc执行sql
        PreparedStatement statement = connection.prepareStatement(deleteSql);
        statement.executeUpdate();
        statement.close();
    }
    public Object findOne(Class clz,Object id) throws SQLException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        String selectSql = "select * from ";
        List<MyselfMapper> mapperList = ORMConfig.mapperList;
        for (MyselfMapper mapper: mapperList) {
            if (mapper.getClassName().equals(clz.getName())){
                String tableName = mapper.getTableName();
                Object[] ids = mapper.getIdMapper().values().toArray();
                selectSql += tableName + " where " + ids[0].toString() + " = " + id;
                break;
            }
        }
        System.out.println("miniORM query:" + selectSql);
        PreparedStatement statement = connection.prepareStatement(selectSql);
        ResultSet resultSet = statement.executeQuery();
        if (resultSet.next()) {
            Object o = clz.newInstance();
            for (MyselfMapper mapper: mapperList) {
                if (mapper.getClassName().equals(clz.getName())) {
                    Map<String, String> propMapper = mapper.getPropMapper();
                    Set<String> columns = propMapper.keySet();
                    for (String column: columns) { // 属性名
                        Field field = clz.getDeclaredField(column);
                        field.setAccessible(true);
                        field.set(o, resultSet.getObject(column));
                    }
                }
                break;
            }
            statement.close();
            resultSet.close();
            return o;
        } else {
            return null;
        }

    }
}

